package com.cmpe.group6.storyroad.ListAdapters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.cmpe.group6.storyroad.EditStory;
import com.cmpe.group6.storyroad.ProfileActivity;
import com.cmpe.group6.storyroad.R;
import com.cmpe.group6.storyroad.Utils;
import com.cmpe.group6.storyroad.jsonClasses.ServerResponseObject;
import com.google.gson.Gson;

/** List Adapter to Show StoryView type lists.
 *
 */
public class MostRecentAdapter extends BaseAdapter {
	Context context;
	List<String> rowItems;
	List<String> ratings;
	List<String> tags;
	List<String> ids;
	boolean isSelfProfile;

	/**
	 * @param context Current context.
	 * @param items Titles of the stories.
	 * @param ratings Ratings of the stories
	 * @param tags Tags of the stories.
	 * @param ids Ids of the stories.
	 */
	public MostRecentAdapter(Context context, List<String> items,
			List<String> ratings, List<String> tags, List<String> ids) {
		this.context = context;
		this.rowItems = items;
		this.ratings = ratings;
		this.tags = tags;
		this.ids = ids;
		isSelfProfile = false;
	}

	/** ViewHolder class for quicker generation.
	 *
	 */
	private class ViewHolder {
		TextView txtTitle;
		TextView txtDescRatings;
		TextView txtDescTags;
		Button editButton;
		Button deleteButton;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return this.rowItems.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return this.ids.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;

		final int pos = position;
		LayoutInflater mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_item, null);
			holder = new ViewHolder();
			holder.txtDescRatings = (TextView) convertView
					.findViewById(R.id.desc_rating);
			holder.txtDescTags = (TextView) convertView
					.findViewById(R.id.desc_tags);
			holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
			holder.editButton = (Button) convertView
					.findViewById(R.id.edit_button);
			holder.deleteButton = (Button) convertView
					.findViewById(R.id.delete_button);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		String title = this.rowItems.get(position);
		String rating = this.ratings.get(position);
		String tag = this.tags.get(position);
		holder.txtTitle.setText(title);
		holder.txtDescRatings.setText("Rating: " + rating);
		holder.txtDescTags.setText(tag);
		if (isSelfProfile) {
			holder.editButton.setVisibility(View.VISIBLE);
			holder.editButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					Intent editIntent = new Intent(context,
							EditStory.class);
					editIntent.putExtra("storyId", ids.get(pos));
					context.startActivity(editIntent);
				}
			});
			
			holder.deleteButton.setVisibility(View.VISIBLE);
			holder.deleteButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					new DeleteStoryTask().execute(pos);
				}
			});
		}

		return convertView;
	}

	/**
	 * @return Is the target profile user's own profile.
	 */
	public boolean isSelfProfile() {
		return isSelfProfile;
	}

	/**
	 * @param isSelfProfile Is the target profile user's own profile.
	 */
	public void setSelfProfile(boolean isSelfProfile) {
		this.isSelfProfile = isSelfProfile;
	}

	/**
	 * Represents an asynchronous Delete Story task for deleting a story
	 * from the server.
	 */
	public class DeleteStoryTask extends AsyncTask<Integer, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Integer... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "DeleteStory");
			ServerResponseObject responseObject = new ServerResponseObject();
			int position = params[0];

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				nameValuePairs.add(new BasicNameValuePair("story_id", ids
						.get(position)));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				responseObject = gson.fromJson(jsonResponse,
						ServerResponseObject.class);

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}
			if (responseObject.isDeleteSuccess()) {
				return true;
			} else {
				return false;
			}
		}

		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(context, "Connection Error", Toast.LENGTH_SHORT)
						.show();
			} else {
				Intent restartIntent = new Intent(context,
						ProfileActivity.class);
				restartIntent.putExtra("targetname", ((Activity) context)
						.getIntent().getStringExtra("targetname"));
				context.startActivity(restartIntent);
			}
		}

		@Override
		protected void onCancelled() {

		}
	}

}
